//
//  ScorePayViewController.m
//  JiuLe
//
//  Created by SunChao on 16/10/12.
//  Copyright © 2016年 Fine. All rights reserved.
//

#import "ScorePayViewController.h"
#import "MallRequestManager.h"
#import "SVProgressHUD.h"
#import "AddressModel.h"
#import "AllAddressViewController.h"
#import "AddressViewController.h"
#import "OrderGoodsInfoModel.h"
#import "OrderDetailViewController.h"
@interface ScorePayViewController ()<UIAlertViewDelegate>
@property (nonatomic,strong)NSMutableArray *addressData;//地址信息
@property (nonatomic,strong)NSMutableArray *dataSource;//商品信息
@property (nonatomic,strong)NSString *orderId;
@end

@implementation ScorePayViewController
-(void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self name:newAddress object:nil];
    [[NSNotificationCenter defaultCenter]removeObserver:self name:changeAddressNoti object:nil];
}
- (void)viewDidLoad {
    self.OKButton.layer.cornerRadius = 25;
     [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(changeAddress:) name:changeAddressNoti object:nil];
    //首次添加新地址
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(newAddress) name:newAddress object:nil];
    //获取地址信息
    self.OKButton.enabled = NO;
    NSString *userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userID"];
    NSString *token = [[NSUserDefaults standardUserDefaults]objectForKey:@"token"];
    NSMutableDictionary *params = [NSMutableDictionary new];
    [params setValue:userId forKey:@"user_id"];
    [params setValue:token forKey:@"token"];
    [SVProgressHUD showWithStatus:@"加载中.." maskType:SVProgressHUDMaskTypeClear];
    [MallRequestManager post:Queryreceivingaddress RequestParams:params FinishBlock:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        [SVProgressHUD dismiss];
        if (connectionError) {
            NSLog(@"connectionError:%@",connectionError);
        }else
        {
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];//转换数据格式
            if ([dic.allKeys containsObject:@"result"]) {
                NSArray *result = [dic objectForKey:@"result"];
                if (result.count == 0) {
                    //跳转地址编辑页
                    [self performSelectorOnMainThread:@selector(pushToAddressVC) withObject:nil waitUntilDone:YES];
                    return ;
                }else
                {
                    self.addressData = [NSMutableArray new];
                    for (NSDictionary *dic in result) {
                        [self.addressData addObject:[AddressModel appWithDict:dic]];
                        
                    }
                    
                    [self performSelectorOnMainThread:@selector(createUI) withObject:nil waitUntilDone:NO];
                }
                
            }
        }
    }];

}
- (void)pushToAddressVC
{
    AddressViewController *address = [[UIStoryboard storyboardWithName:@"MallViewController" bundle:nil]instantiateViewControllerWithIdentifier:@"address"];
    [self.navigationController pushViewController:address animated:YES];
}
- (void)newAddress
{
        NSString *userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userID"];
        NSString *token = [[NSUserDefaults standardUserDefaults]objectForKey:@"token"];
        NSMutableDictionary *params = [NSMutableDictionary new];
        [params setValue:userId forKey:@"user_id"];
        [params setValue:token forKey:@"token"];
        [SVProgressHUD showWithStatus:@"加载中.." maskType:SVProgressHUDMaskTypeClear];
        [MallRequestManager post:Queryreceivingaddress RequestParams:params FinishBlock:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
            [SVProgressHUD dismiss];
            if (connectionError) {
                NSLog(@"connectionError:%@",connectionError);
            }else
            {
                NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];//转换数据格式
                if ([dic.allKeys containsObject:@"result"]) {
                    NSArray *result = [dic objectForKey:@"result"];
                    self.addressData = [NSMutableArray new];
                    for (NSDictionary *dic in result) {
                        [self.addressData addObject:[AddressModel appWithDict:dic]];
                    }
                    [self performSelectorOnMainThread:@selector(reloadUI) withObject:nil waitUntilDone:NO];
                }
            }
        }];
}
- (void)reloadUI
{
    NSLog(@"dataSource:%@",self.dataSource);
    if (self.dataSource.count>0) {
        AddressModel *model = [self.dataSource objectAtIndex:0];
        self.nameLabel.text = model.name;
        self.phoneLabel.text = model.tel;
        self.addressLabel.text = [NSString stringWithFormat:@"%@ %@ %@ %@",model.province,model.city,model.district,model.address];
        [self.tableView reloadData];
    }else
    {
        [[NSNotificationCenter defaultCenter]postNotificationName:noAddressOfScore object:nil];
    }
    
}
- (void)changeAddress:(NSNotification *)text
{
    NSLog(@"text:%@",text.userInfo);
    AddressModel *model = [text.userInfo objectForKey:@"newAddress"];
    self.nameLabel.text = model.name;
    self.phoneLabel.text = model.tel;
    self.addressLabel.text = [NSString stringWithFormat:@"%@ %@ %@ %@",model.province,model.city,model.district,model.address];
    [[NSNotificationCenter defaultCenter]postNotificationName:removeGoodSelectVC object:nil];
    [self.tableView reloadData];
    //刷新地址信息
}
- (void)createUI
{
    //默认地址为数组第一个
    if (self.addressData.count>0) {
        AddressModel *model = self.addressData[0];
        self.nameLabel.text = model.name;
        self.phoneLabel.text = model.tel;
        self.addressLabel.text = [NSString stringWithFormat:@"%@ %@ %@ %@",model.province,model.city,model.district,model.address];
        self.OKButton.enabled = YES;
    }else
    {
        self.nameLabel.text = @"";
        self.phoneLabel.text = @"";
        self.addressLabel.text = @"";
    }
    [self.tableView reloadData];
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self.tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.row ==0) {
        if (self.addressData.count == 0) {

        }else
        {
            AllAddressViewController *all = [[AllAddressViewController alloc]init];
            [self.navigationController pushViewController:all animated:YES];
        }
    }
}
- (IBAction)OKButtonClicked:(UIButton *)sender
{
    if (self.addressLabel.text.length == 0) {
        [SVProgressHUD showErrorWithStatus:@"请填写收货地址"];
        return;
    }
        [self requestOrderData];
}
- (void)requestOrderData
{
    NSMutableDictionary *params = [NSMutableDictionary new];
    NSString *userId = [[NSUserDefaults standardUserDefaults]objectForKey:@"userID"];
    NSString *token = [[NSUserDefaults standardUserDefaults]objectForKey:@"token"];
    NSDictionary *goodDic = [self.dataDic objectForKey:@"goodsInfo"];
    NSString *goodid = [goodDic objectForKey:@"goodid"];
    NSNumber *num = [NSNumber numberWithInt:[[self.dataDic objectForKey:@"number"] intValue]];
    NSString *standardid = [goodDic objectForKey:@"id"];
    if ([standardid isEqualToString:@""]) {
        standardid = @"0";
    }
    AddressModel *model = [self.addressData objectAtIndex:0];
    NSString *address = model.uid;
    NSString *invoicetitle = @"xiaolipin";//可为空
    NSString *message = @"xiaolipin";//可为空
    NSString *order_type = @"1";
    NSString *isexchange = @"1";
    [params setValue:userId forKey:@"user_id"];
    [params setValue:token forKey:@"token"];
    [params setObject:goodid forKey:@"good_id"];
    [params setObject:standardid forKey:@"standard_id"];
    [params setObject:num forKey:@"good_num"];
    [params setObject:invoicetitle forKey:@"invoicetitle"];
    [params setObject:address forKey:@"addressid"];
    [params setObject:isexchange forKey:@"isexchange"];
    [params setObject:message forKey:@"message"];
    [params setObject:order_type forKey:@"order_type"];
    [SVProgressHUD showWithStatus:@"加载中.." maskType:SVProgressHUDMaskTypeClear];
    [MallRequestManager post:Queryaddorder RequestParams:params FinishBlock:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        [SVProgressHUD dismiss];
        if (connectionError) {
            NSLog(@"connect:%@",connectionError);
        }else{
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];//转换数据格式
            NSDictionary *result = [dic objectForKey:@"result"];
            self.orderId = [result objectForKey:@"orderid"];
            if ([[dic objectForKey:@"status"]intValue] ==207&&[[dic objectForKey:@"result"]isKindOfClass:[NSNull class]]&&[[dic objectForKey:@"message"] isEqualToString:@"该商品库存不足"]) {
                [SVProgressHUD showErrorWithStatus:@"该商品库存不足"];
                return ;
            }
            if ([[dic objectForKey:@"status"]intValue] ==208&&[[dic objectForKey:@"result"]isKindOfClass:[NSNull class]]&&[[dic objectForKey:@"message"] isEqualToString:@"您的积分不够"]) {
                [self performSelectorOnMainThread:@selector(alterViewShow) withObject:nil waitUntilDone:YES];
            }else
            {
                [SVProgressHUD showSuccessWithStatus:@"支付成功"];
                [self performSelectorOnMainThread:@selector(PushAfterDelay) withObject:nil waitUntilDone:YES];
            }
        }
    }];
}
- (void)alterViewShow
{
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"" message:@"积分不足,无法购买" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"赚积分", nil];
    alertView.delegate = self;
    [alertView show];
}

- (void)PushAfterDelay
{
    [self performSelector:@selector(PushToOrderVC) withObject:nil afterDelay:1.0f];
}

- (void)PushToOrderVC
{
    //OrderGoodsInfoModel *model = [self.dataSource objectAtIndex:0];
    //NSDictionary *dic = model.goodinfo;
    
    OrderDetailViewController *orderDetail = [[UIStoryboard storyboardWithName:@"PersonalViewController" bundle:nil] instantiateViewControllerWithIdentifier:@"OrderDetailViewController"];
    orderDetail.strOrderid = self.orderId;
    [self.navigationController pushViewController:orderDetail animated:YES];
}
#pragma mark AlterViewDelegate
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex ==0) {
        NSLog(@"button:%ld",buttonIndex);
    }else if (buttonIndex ==1)
    {
        NSLog(@"button:%ld",buttonIndex);
    }
    
}
@end
